package com.example.controller;

import com.example.mapper.one.GraduateMapper;
import com.example.mapper.one.ThesisMapper;
import com.example.mapper.one.TreeMapper;
import com.example.mapper.two.Neo4j;
import com.example.pojo.*;
import com.example.service.ThesisService;
import com.example.service.TreeService;
import com.example.util.ResultUtil;
import com.example.util.token.TokenUtil;
import com.example.util.token.UserLoginToken;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hankcs.hanlp.corpus.tag.Nature;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.tokenizer.StandardTokenizer;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/thesisInfo")

public class ThesisInfoController {
    @Resource
    private TreeService treeService;

    @Resource
    private TreeMapper treeMapper;

    @Resource
    private ThesisMapper thesisMapper;

    @Resource
    private GraduateMapper graduateMapper;

    @Resource
    private ThesisService thesisService;

    @Resource
    private Neo4j neo4j;

    /*获取毕业生数据*/
    @UserLoginToken
    @RequestMapping("/getTheData")
    public Map getGraData(@RequestParam(required = false) Integer grade, @RequestParam(required = false) Integer major, @RequestParam(required = false) Integer team,
                          @RequestParam(required = false) Integer sno, @RequestParam(required = false) String sname,
                          @RequestParam Integer currentPage, @RequestParam Integer pageSize){
        PageHelper.startPage(currentPage, pageSize);
        List<ThesisInfo> list = thesisMapper.getThesisData(grade,major,team,sno,sname);
        PageInfo<ThesisInfo> pageInfo = new PageInfo<>(list);
        // getTotal获取总条数
        pageInfo.getTotal();
        // 获取当前页的结果集
        pageInfo.getList();
        Map resultMap = new HashMap();
        resultMap.put("total",pageInfo.getTotal());
        resultMap.put("tableData",pageInfo.getList());
        return resultMap;
    }

    @UserLoginToken
    @GetMapping("/getKeywords")
    public Map getKeywords(@RequestParam(required = true)String title){
        Map resultMap = new HashMap();
        List<Term> termList = StandardTokenizer.segment(title);
        List wordList = new ArrayList();
        for(Term term:termList){
            /*单词名词和中文名词*/
            if(term.nature.toString() == "nx" || term.nature.toString() == "n"){
                wordList.add(term.word);
            }
        }
        resultMap.put("code",200);
        resultMap.put("keywordList",wordList);
        return resultMap;
    }

    @PostMapping("/uploadThesis")
    public Result uploadThesis(@RequestParam(required = false,value = "sNo") Integer sNo, @RequestParam(required = false,value = "sName") String sName, @RequestParam(required = false,value = "thesisTitle") String thesisTitle,
                                @RequestParam(required = false,value = "keywords") String keywords, @RequestParam(required = false,value = "thesisFileName") String thesisFileName, @RequestParam(required = false,value = "enclosureFileName") String enclosureFileName,
                                @RequestParam(required = false,value = "gradeId") Integer gradeId, @RequestParam(required = false,value = "majorId") Integer majorId, @RequestParam(required = false,value = "teamId") Integer teamId,
                                @RequestParam("file") MultipartFile file){
        int isExist = thesisMapper.queryExit(sNo);
        if(isExist > 0){
            String path = "";
            String baseThesisFileName = thesisMapper.getThesisFileName(sNo);
            baseThesisFileName = baseThesisFileName.substring(baseThesisFileName.lastIndexOf("/"));
            boolean isDelete = FileSystemUtils.deleteRecursively(new File("D:\\ideaProject\\upload\\"+sNo+"\\"+baseThesisFileName));
            if(!isDelete){
                System.out.println("删除论文文件失败");
            }
        }
        String savePath = mkFile(file,sNo);
        ThesisInfo thesisInfo = new ThesisInfo(sNo,sName,thesisTitle,keywords,"/thesis/" + savePath,enclosureFileName,gradeId,majorId,teamId);
        int isUpload;
//        修改
        if(isExist > 0){
            isUpload = thesisMapper.updateThesisInfo(thesisInfo);
        }
//        增加
        else{
            isUpload = thesisService.addThesisInfo(thesisInfo);
        }
        Result result;
        if(isUpload > 0){
            result = ResultUtil.success("上传成功");
        }else{
            result = ResultUtil.error(500,"上传失败");
        }
        return result;
    }

    @PostMapping("/uploadEnclosure")
    public Result uploadEnclosure(@RequestParam(required = false,value = "sNo") Integer sNo,
                               @RequestParam("file") MultipartFile file){
        String baseEnclosureFileName = thesisMapper.getEnclosureFileName(sNo);
        if(baseEnclosureFileName != null && baseEnclosureFileName.length() > 0 ){
            baseEnclosureFileName = baseEnclosureFileName.substring(baseEnclosureFileName.lastIndexOf("/"));
            boolean isDelete = FileSystemUtils.deleteRecursively(new File("D:\\ideaProject\\upload\\"+sNo+"\\"+baseEnclosureFileName));
            if(!isDelete){
                System.out.println("删除附件文件失败");
            }
        }
        String savePath = mkFile(file,sNo);
        int addEnclosureFile = thesisMapper.setEnclosureFile("/thesis/" + savePath,sNo);
        Result result = new Result();
        return result;
    }

    public String mkFile(MultipartFile file,Integer sNo){
        if (file.isEmpty()) System.out.println("上传失败");
        String filePath = ""; // 文件保存的位置
        String originalFilename = file.getOriginalFilename();
        // 加上时间戳生成新的文件名,防止重复 newFileName = "1595511980146a.jpg"
        String newFileName = System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
        filePath = "D:\\ideaProject\\upload\\" + sNo + "/" + newFileName;
        try {
            File file1 = new File(filePath);
            if (!file1.exists()) file1.mkdirs(); // 要是目录不存在,创建一个
            file.transferTo(file1);              // 保存起来
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sNo + "/" + newFileName;
    }


    /*单个删除论文*/
    @UserLoginToken
    @RequestMapping("/delThesis")
    public Result delThesis(@RequestParam Integer sNo){
        int isDel = thesisMapper.deleteThe(sNo);
        boolean isDelete = FileSystemUtils.deleteRecursively(new File("D:\\ideaProject\\upload\\"+sNo));
        if(!isDelete){
            System.out.println("删除目录失败");
        }
        Result result;
        if(isDel > 0){
            result = ResultUtil.success("删除成功");
        }
        else{
            result = ResultUtil.error(500,"删除失败");
        }
        return result;
    }

    /*批量删除论文*/
    @UserLoginToken
    @RequestMapping("/batchDelThesis")
    public Result batchDelThesis(@RequestParam String ids){
        String[] idArray=ids.split(",");
        Result result;
        int isDel = 0;
        for(int i = 0;i < idArray.length;i++){
            int id = Integer.parseInt(idArray[i]);
            boolean isDelete = FileSystemUtils.deleteRecursively(new File("D:\\ideaProject\\upload\\"+id));
            if(!isDelete){
                System.out.println("删除目录失败");
            }
            isDel = isDel + thesisMapper.deleteThe(id);
        }
        if(isDel > 0){
            result = ResultUtil.success("删除成功");
        }
        else{
            result = ResultUtil.error(500,"删除失败");
        }
        return result;
    }

    @UserLoginToken
    /*只修改部分论文数据（不上传文件）*/
    @GetMapping("/updateTiltleKeyword")
    public Result updateTiltleKeyword(@RequestParam(value = "sNo") Integer sNo, @RequestParam(value = "title") String title,
                                      @RequestParam(required = false,value = "keywords") String keywords){
        Result result;
        int isUpdate = thesisMapper.updateThesisPart(sNo,title,keywords);
        if(isUpdate > 0){
            result = ResultUtil.success("删除成功");
        }
        else{
            result = ResultUtil.error(500,"删除失败");
        }
        return result;
    }

    /*热门技术*/
    @UserLoginToken
    @GetMapping("/hotTechnical")
    public Map hotTechnical(@RequestParam Integer majorId){
        List<String> keywordList = thesisService.getKeywords(majorId);
        Map map = new HashMap();
        map.put("code",200);
        map.put("keywordList",keywordList);
        return map;
    }

    /*获取所有系*/
    @UserLoginToken
    @GetMapping("/getGrade")
    public Map getGrade(){
        Map resultMap = new HashMap();
        List gradeList = treeService.getGradeList();
        resultMap.put("code",200);
        resultMap.put("gradeList",gradeList);
        return resultMap;
    }

    /*获取该系下的所有专业*/
    @UserLoginToken
    @GetMapping("/getMajor")
    public Map getMajor(@RequestParam Integer gradeId){
        Map resultMap = new HashMap();
        List<Tree> majorList = treeMapper.getChildTree(gradeId);
        resultMap.put("code",200);
        resultMap.put("majorList",majorList);
        return resultMap;
    }

    /*获取节点和关系*/
    @UserLoginToken
    @GetMapping("/getNodeData")
    public Map getNodeData(@RequestParam Integer majorId){
        Map resultMap = new HashMap();
        List<Node> nodeList = neo4j.getNodeData(majorId);
        List<Link> linkList = neo4j.getLinkData(majorId);
        resultMap.put("code",200);
        resultMap.put("nodeList",nodeList);
        resultMap.put("linkList",linkList);
        return resultMap;
    }

    /*根据学号获取姓名*/
    @UserLoginToken
    @RequestMapping("querySname")
    public Result querySname(@RequestParam(required = true) Integer sNo){
        String sname = graduateMapper.querySname(sNo);
        Result result;
        if(sname != null){
            int recordCount = thesisMapper.queryExit(sNo);
            if(recordCount > 0){
                result = ResultUtil.error(500,"该学生论文已上传，如需修改请移步编辑");
            } else {
                result = ResultUtil.success(sname);
            }
        }
        else{
            result = ResultUtil.error(500,"不存在该学生");
        }
        return result;
    }
}
